//
//  DateUtils.swift
//  LXSwift_Example
//
//  Created by 广东万商通科技有限公司 on 2024/12/18.
//  Copyright © 2024 CocoaPods. All rights reserved.
//

import Foundation

public class DateUtils {
    
    public  static let shared = DateUtils() // 单例模式
    
    private let dateFormatter = DateFormatter()
    
    private init() {} // 防止外部初始化
    
    /// 设置日期格式
    public  func setDateFormat(_ format: String) {
        dateFormatter.dateFormat = format
    }
    
    /// 设置时区
    public  func setTimeZone(_ timeZone: String) {
        dateFormatter.timeZone = TimeZone(identifier: timeZone)
    }
    
    ///设置locale
    public  func setLocale(_ locale:String){
        dateFormatter.locale = Locale(identifier: locale)
    }
    
    /// 字符串转 Date
    public  func date(from string: String) -> Date? {
        return dateFormatter.date(from: string)
    }
    
    /// Date 转字符串
    public func string(from date: Date) -> String {
        return dateFormatter.string(from: date)
    }
    
    /// 时间戳 (秒) 转 Date
    public  func date(from timestamp: TimeInterval) -> Date {
        return Date(timeIntervalSince1970: timestamp)
    }
    
    /// 毫秒时间戳转Date
    public  func dateFromMilli(from milliTimeStamp: TimeInterval) -> Date{
        return Date(timeIntervalSince1970: milliTimeStamp/1000)
    }
    
    /// Date 转时间戳 (秒)
    public  func timestamp(from date: Date) -> TimeInterval {
        return date.timeIntervalSince1970
    }
    
    /// Date 转毫秒时间戳
    public  func milliTimestamp(from date: Date) -> TimeInterval{
        return date.timeIntervalSince1970 * 1000
    }
    
    
    /// 比较两个日期
    public  func compare(date1: Date, date2: Date) -> ComparisonResult {
        return date1.compare(date2)
    }
    
    /// 判断两个日期是否为同一天
    public  func isSameDay(date1: Date, date2: Date) -> Bool {
        return Calendar.current.isDate(date1, inSameDayAs: date2)
    }
    
    /// 日期加减
    public   func date(byAdding component: Calendar.Component, value: Int, to date: Date) -> Date? {
        return Calendar.current.date(byAdding: component, value: value, to: date)
    }
    
    /// 获取日期组成部分
    public   func component(_ component: Calendar.Component, from date: Date) -> Int {
        return Calendar.current.component(component, from: date)
    }
    
    /// 获取两个日期的时间间隔
    public  func dateComponents(_ components: Set<Calendar.Component>, from date1: Date, to date2: Date) -> DateComponents {
        return Calendar.current.dateComponents(components, from: date1, to: date2)
    }
}
